#include<iostream>
#include<string>
#include"Socket.hpp"
#include"Protocol.hpp" 
#include<time.h>
#include<unistd.h>
#include<assert.h>
using namespace std;
void Usage(string proc)
{
    cout<<"\nUsage"<<proc<<"serveip serveport\n"<<endl;
}
// ./clintcal ip ,port
int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);
    Sock sockfd;
    sockfd.Socket();
    bool r =sockfd.Connect(serverip,serverport);
    if(!r) return 1;

    srand(time(nullptr)^getpid());
    int cnt=10;
    string opers="+-*/%=-=&^";
    string cmz;
    while(cnt--)
    {
        cout<<"第"<<cnt<<"次测试"<<endl;
        int x=rand()%100+1;
        usleep(1111);//为了更随机
        int y=rand()%100;
        usleep(1111);
        char oper=opers[rand()%opers.size()];

        //初始化,序列化加包头符合协议
        request req(x,y,oper);
        req.DebugPrint();
        string package;
        req.Serialize(package);
        package=Encode(package);
        //写过去
        write(sockfd.Fd(),package.c_str(),package.size());
        
        //读回来结果
        char buff[128];
        ssize_t n=read(sockfd.Fd(),buff,sizeof(buff));
        if(n>0)
        {
            buff[n]=0;
            cmz+=buff;
            string content;
            bool r=Decode(cmz,content);
            assert(r);
            response res;
            res.DSerialize(content);//反序列化，"result code"
            res.DebugPrint();
        }
       sleep(1);
    }
    sockfd.Close();
    return 0;
}